package com.mail

import grails.converters.JSON

class MailController {

    //注入邮件服务
    def mailService

    def index() {

    }

    /**
     *  发送带html的邮件
     *  带昵称
     *  to 收件人，字符串，多个收件人有英文逗号隔开
     */
    def sendHtml() {

        def info = [:]

        //收件人
        String recipients = params.recipients
        //昵称
        String nickname = params.nickname

        try {
            mailService.sendMail {
                //application.yml中配置的发件人
                from "${nickname}<${grailsApplication.config.grails.mail.username}>"
                to "${nickname}<${recipients}>" //"<昵称>邮箱"
                subject '邮件标题'
//                body(view:'template',model:[message:'测试邮件，收到此邮件不用回复！'])
                html(view:'template',model:[message:'测试邮件，收到此邮件不用回复！'])
                //html "<a href='http://www.baidu.com'>百度</a>"
            }
            info = [result:true, msg: "邮件发送成功！"]
        } catch (e) {
            log.error("邮件发送失败，errorMsg={}",e)
            info = [result:false, msg: "邮件发送失败！"]
        }
        render info as JSON
    }

    /**
     *  发送带附件的邮件
     *  带昵称
     *  方法中必须传text、body、html任意一个才能携带附件
     */
    def sendAttach() {

        def info = [:]

        //收件人
        String recipients = params.recipients
        //昵称
        String nickname = params.nickname

        try {
            mailService.sendMail {

                //多附件
                multipart true

                //application.yml中配置的发件人
                from "${nickname}<${grailsApplication.config.grails.mail.username}>"

                //"<昵称>邮箱"
                to "${nickname}<${recipients}>"

                subject '邮件标题'

                attach (new File("E:\\water.png"))
                text "测试邮件"
            }
            info = [result:true, msg: "邮件发送成功！"]
        } catch (e) {
            log.error("邮件发送失败，errorMsg={}",e)
            info = [result:false, msg: "邮件发送失败！"]
        }
        render info as JSON
    }
}
